﻿using Helper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WPFCouse.Models;

namespace WPFCouse
{
    /// <summary>
    /// TreeViewWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TreeViewWindow : Window
    {
        public TreeViewWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 获取菜单数据
        /// </summary>
        /// <returns></returns>
        private List<MenuInfo> GetMenuList()
        {
            //string sql = "select MenuId,MenuName,ParentId from MenuInfos";
            //SqlDataReader dr = SqlHelper.ExecuteReader(sql, 1);
            List<MenuInfo> list = new List<MenuInfo>();
            //while (dr.Read())
            //{
            //    MenuInfo menu = new MenuInfo();
            //    menu.MenuId = (int)dr["MenuId"];
            //    menu.MenuName = dr["MenuName"].ToString();
            //    menu.ParentId = (int)dr["ParentId"];
            //    list.Add(menu);
            //}
            //dr.Close();
            return list;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //代码添加节点    比较烦锁   不可取
            //TreeViewItem item1 = new TreeViewItem();
            //item1.Header = "基础资料";
            //TreeViewItem rootNode = tvList.Items[0] as TreeViewItem;
            //rootNode.Items.Insert(1,item1);//在指定位置插入节点

            //TreeViewItem item11 = new TreeViewItem();
            //item11.Header = "商品管理";
            //item1.Items.Add(item11);

            //TreeViewItem item12 = new TreeViewItem();
            //item12.Header = "仓库管理";
            //item1.Items.Add(item12);

            //TreeViewItem item13 = new TreeViewItem();
            //item13.Header = "单位管理";
            //item1.Items.Add(item13);

            //tvList.Items.Clear();//节点清空
            //List<MenuInfo> menuList = GetMenuList();
            ////调用递归加载节点的方法
            //AddTreeViewItems(menuList, null, 0);
          
        }

        //定义一个递归加载方法
        private void AddTreeViewItems(List<MenuInfo> allMenus, TreeViewItem pItem, int parentId)
        {
            var subList = allMenus.Where(m => m.ParentId == parentId);
            foreach (var mi in subList)
            {
                TreeViewItem mItem = new TreeViewItem();
                mItem.Header = mi.MenuName;
                if (pItem != null)
                    pItem.Items.Add(mItem);//子节点
                else
                    tvList.Items.Add(mItem);//根节点
                mItem.IsExpanded = true;
                AddTreeViewItems(allMenus, mItem, mi.MenuId);
            }
        }
    }
}
